package cn.com.xinjinfu.pdoulcProduct.fragment;


import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;

import org.json.JSONObject;

import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Map;

import cn.com.xinjinfu.pdoulcProduct.R;
import cn.com.xinjinfu.pdoulcProduct.activity.FixedProduct.FirstInvestAct;
import cn.com.xinjinfu.pdoulcProduct.activity.FixedProduct.FixedProductInfo;
import cn.com.xinjinfu.pdoulcProduct.adapter.AAdapter;
import cn.com.xinjinfu.pdoulcProduct.adapter.BAdapter;
import cn.com.xinjinfu.pdoulcProduct.adapter.MyBaseAdapter;
import cn.com.xinjinfu.pdoulcProduct.common.ConstantValues;
import cn.com.xinjinfu.pdoulcProduct.engine.DataHandler;
import cn.com.xinjinfu.pdoulcProduct.entity.HomeListBean;
import cn.com.xinjinfu.pdoulcProduct.entity.HomeListBean.Bid;
import cn.com.xinjinfu.pdoulcProduct.entity.Page;
import cn.com.xinjinfu.pdoulcProduct.entity.User;
import cn.com.xinjinfu.pdoulcProduct.manager.AccountManager;
import cn.com.xinjinfu.pdoulcProduct.manager.L;
import cn.com.xinjinfu.pdoulcProduct.manager.ToastManager;
import cn.com.xinjinfu.pdoulcProduct.utils.SharedPreferencesUtils;
import cn.com.xinjinfu.pdoulcProduct.xlistview.XListView;

/**
 * Created by zhouwenbo on 15/7/2.
 * 项目列表fragment
 */
public class ProductListFragment extends Fragment implements XListView.IXListViewListener {

    private int currPage;
    /**
     * list view
     */
    private XListView mListView;
    private HomeListBean homeList;
    private ArrayList<Page> pageList;
    private ArrayList<Page> newpage;
    private TextView new_name,xian_e,new_pra,new_time,time_pro;

    /**
     * 列表类型，interest or recommond
     */
    private String mType;
    LinearLayout no_invest_view;
    private MyBaseAdapter myAdapter;
    private RequestQueue requen;
    private Activity mActivity;
    private View headerView;
    private Bid bid;

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        this.mActivity = activity;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_product_list, container, false);
        mListView = (XListView) view.findViewById(R.id.xListView);
        mListView.setPullLoadEnable(true);// 是否显示下拉刷新和上啦加载
        mListView.setPullRefreshEnable(true);
        mListView.setXListViewListener(this);
        no_invest_view = (LinearLayout) view.findViewById(R.id.no_invest_view);

        //首投 控件
        headerView = LayoutInflater.from(getActivity()).inflate(R.layout.new_project_header,null);
        new_name = ((TextView) headerView.findViewById(R.id.new_name));
        xian_e = ((TextView) headerView.findViewById(R.id.xian_e));
        new_pra = ((TextView) headerView.findViewById(R.id.new_pra));
        new_time = ((TextView) headerView.findViewById(R.id.new_time));
        time_pro = ((TextView) headerView.findViewById(R.id.time_pro));
        headerView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent();
                intent.putExtra("bidId", bid.getBidId() + "");
                intent.putExtra("title", bid.getBidTitle() + "");
                startActivity(intent.setClass(mActivity, FirstInvestAct.class));
            }
        });
        //可以添加多个HeaderView
//        mListView.addHeaderView(headerView);
        return view;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //fragment 非中断保存,也就是说,activity出现销毁,后fragment不被销毁,解决有时候滑不下来的问题
        //setRetainInstance(true);
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        currPage = 1;
        Bundle bundle = getArguments();
        mType = bundle.getString("type");
        requen = Volley.newRequestQueue(mActivity);
        loadData(currPage);
    }

    /**
     * 网络请求
     */
    private void loginRequest(String teyp, int currPage) {
        final Map<String, String> parameters = DataHandler.getParameters(teyp);
        User user = AccountManager.getInstance().getUser();
        if (user != null && user.getCurrUser().isLogged() && teyp.equals("1203")) {
            parameters.put("id", user.getCurrUser().getSign());
        }
        parameters.put("currPage", currPage + "");
        parameters.put("pageSize", "9");
        JsonObjectRequest request = new JsonObjectRequest(DataHandler.getBuildUrl(parameters), null, succeedRespon, error);
        request.setRetryPolicy(new DefaultRetryPolicy(ConstantValues.TIMEOUT, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        requen.add(request);
    }
    private Response.ErrorListener error = new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            if (currPage != 1){
                DataHandler.errorHandler(mActivity, error);
                mListView.removeHeaderView(headerView);
            }
            currPage--;
        }
    };
    private Response.Listener<JSONObject> succeedRespon = new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject jobj) {
            L.i(jobj.toString());
            onLoad();
            homeList = JSON.parseObject(jobj.toString(), HomeListBean.class);
            if (currPage == 1) {
                //新手标数据加载
                bid = homeList.getBid();
                if (bid == null){
                    mListView.removeHeaderView(headerView);
                }else {
                    if (mListView.getHeaderViewsCount()<2){
                        mListView.addHeaderView(headerView);
                    }
                    new_name.setText(bid.getBidTitle());
                    xian_e.setText("单笔限额" + homeList.getMaxNewBidInvestAmount() + "元");
                    new_pra.setText(NumberFormat.getInstance().format(bid.getBidApr()) + "");
                    new_time.setText(bid.getBidPeriod() + "");
                    //新手标 期限单位现在都为：天
                    if (bid.getBidPeriodUnit() == 1) {
                        time_pro.setText("天");
                    } else if (bid.getBidPeriodUnit() == 0) {
                        time_pro.setText("月");
                    } else {
                        time_pro.setText("年");
                    }
                }
                if (TextUtils.equals(mType, "recommend")) {
                    SharedPreferencesUtils.saveUserInfo(mActivity, "fixedList1", jobj.toString());
                    pageList = (ArrayList<Page>) homeList.getTermBids().getPage();
                } else {
                    SharedPreferencesUtils.saveUserInfo(mActivity, "transferList1", jobj.toString());
                    pageList = (ArrayList<Page>) homeList.getTermTransfers().getPage();
                }
                if (!pageList.isEmpty()) {
                    myAdapter.setMyList(pageList);
                    no_invest_view.setVisibility(View.GONE);
                } else {
                    no_invest_view.setVisibility(View.VISIBLE);
                }
            } else {
                if (TextUtils.equals(mType, "recommend")) {
                    newpage = (ArrayList<Page>) homeList.getTermBids().getPage();
                } else {
                    newpage = (ArrayList<Page>) homeList.getTermTransfers().getPage();
                }
                if (newpage.isEmpty()) {
                    Toast.makeText(mActivity, "没有更多数据",Toast.LENGTH_SHORT).show();
                } else {
                    myAdapter.addList(newpage);
                }
            }
        }
    };

    private void loadData(int currPage) {
        if (TextUtils.equals(mType, "recommend")) {
            myAdapter = new AAdapter(getActivity());
            loginRequest("1203", currPage);
            String fixedList1 = SharedPreferencesUtils.getUserInfo(mActivity, "fixedList1");
            if (fixedList1 != "") {
                homeList = JSON.parseObject(fixedList1, HomeListBean.class);
                if (homeList != null) {
                    pageList = (ArrayList<Page>) homeList.getTermBids().getPage();
                    if (!pageList.isEmpty()) {
                        myAdapter.setMyList(pageList);
                        no_invest_view.setVisibility(View.GONE);
                    } else {
                        no_invest_view.setVisibility(View.VISIBLE);
                    }
                }
            }
        } else {
            mListView.removeHeaderView(headerView);
            myAdapter = new BAdapter(getActivity());
            loginRequest("1204", currPage);
            String transferList1 = SharedPreferencesUtils.getUserInfo(mActivity, "transferList1");
            if (transferList1 != "") {
                homeList = JSON.parseObject( transferList1 , HomeListBean.class);
                if (homeList != null) {
                    pageList = (ArrayList<Page>) homeList.getTermTransfers().getPage();
                    if (!pageList.isEmpty()) {
                        myAdapter.setMyList(pageList);
                        no_invest_view.setVisibility(View.GONE);
                    } else {
                        no_invest_view.setVisibility(View.VISIBLE);
                    }
                }
            }
        }
        mListView.setAdapter(myAdapter);
    }

    /**
     * 获取ListView
     *
     * @return listView
     */
    public ListView getListView() {
        return mListView;
    }


    @Override
    public void onRefresh() {
        currPage = 1;
        if (TextUtils.equals(mType, "recommend")) {
            loginRequest("1203", currPage);
        } else {
            loginRequest("1204", currPage);
        }
    }

    @Override
    public void onLoadMore() {
        currPage++;
        if (TextUtils.equals(mType, "recommend")) {
            loginRequest("1203", currPage);
        } else {
            loginRequest("1204", currPage);
        }
    }

    private void onLoad() {
        mListView.stopRefresh();
        mListView.stopLoadMore();
        mListView.setRefreshTime("刚刚");
    }

}